package com.zzy.sqlSession;

import com.zzy.pojo.Configuration;
import com.zzy.pojo.MappedStatement;
import com.zzy.utils.BoundSql;
import com.zzy.utils.GenericTokenParser;
import com.zzy.utils.ParameterMapping;
import com.zzy.utils.ParameterMappingTokenHandler;

import javax.lang.model.element.VariableElement;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件描述: <br>
 * 版权所有: Copyright (c) 2021/5/2<br>
 * 完成日期: 2021/5/2<br>
 *
 * @author zainzhang
 */
public class SimpleExecutor implements Executor {

    private Connection connection = null;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getStatement(configuration, statement, params);
        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 6.封装返回集
        Class<?> resultType = statement.getResultType();
        List<E> resultList = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            E o = (E) resultType.getDeclaredConstructor().newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 获取字段名
                String columnName = metaData.getColumnName(i);
                // 获取值
                Object value = resultSet.getObject(columnName);
                //创建属性描述器，为属性生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                // 获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            resultList.add(o);
        }
        return resultList;
    }

    @Override
    public int update(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getStatement(configuration, statement, params);
        return preparedStatement.executeUpdate();
    }

    private BoundSql getBoundSql(String sql) {
        //标记处理类:主要是配合通用标记解析器GenericTokenParser类完成对配置文件等的解析工作，其中TokenHandler主要完成处理
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        //GenericTokenParser :通用的标记解析器，完成了代码片段中的占位符的解析，然后再根据给定的标记处理器(TokenHandler)来进行表达式的处理
        //三个参数:分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处理器)
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parse, parameterMappings);
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    private PreparedStatement getStatement(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        connection = configuration.getDataSource().getConnection();
        // 2.获取sql语句
        String sql = statement.getBindSql();
        BoundSql boundSql = getBoundSql(sql);
        Class<?> parameterType = statement.getParameterType();
        // 3.获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 4. 设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping mapping = parameterMappingList.get(i);
            String name = mapping.getContent();
            Field field = parameterType.getDeclaredField(name);
            field.setAccessible(true);
            // 参数的值
            Object o = field.get(params[0]);
            // 给占位符赋值
            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }
}
